package cn.itcast.flink.transformation;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author lilulu
 */
public class TransformationReduceDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> source = env.socketTextStream("node1.itcast.cn", 9999);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<Tuple2<String, Integer>> tupleData = source.filter(line -> line.trim().length() > 0)
                .flatMap(
                        new FlatMapFunction<String, Tuple2<String, Integer>>() {
                            @Override
                            public void flatMap(String line, Collector<Tuple2<String, Integer>> collector) throws Exception {
                                String[] words = line.trim().split("\\s+");
                                for (String word : words) {
                                    collector.collect(Tuple2.of(word, 1));
                                }
                            }
                        }
                );
        SingleOutputStreamOperator<Tuple2<String, Integer>> reduceData = tupleData.keyBy(tuple -> tuple.f0).reduce(
                new ReduceFunction<Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> reduce(Tuple2<String, Integer> temp, Tuple2<String, Integer> item) throws Exception {
                        System.out.println("temp = " + temp + ", item = " + item);
                        /*
                        tmp：表示keyBy分组中每个Key对应结果值
                        key -> spark, tmp -> (spark, 10)
                        todo： 如果第一次对key数据聚合，直接将数据赋值给tmp
                        item: 表示使用keyBy分组后组内数据
                        (spark, 1)
                        */
                        Integer historyValue = temp.f1;
                        Integer currentValue = item.f1;
                        int lastValue = historyValue + currentValue;
                        return Tuple2.of(temp.f0, lastValue);
                    }
                }
        );
        // 4. 数据终端-sink
        reduceData.printToErr();
        // 5. 触发执行-execute
        env.execute("TransformationReduceDemo");
    }
}